package com.quectel.mobile.controller.pay;

import com.google.common.base.Preconditions;
import com.quectel.business.pay.PayBusiness;
import com.quectel.business.pay.vo.CreateOrderRequest;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.module.merchant.dto.MerchantVillageDto;
import com.quectel.core.module.merchant.service.MerchantVillageService;
import com.quectel.mobile.controller.BaseController;
import com.quectel.mobile.interceptor.LoginMobileUserSession;
import com.quectel.mobile.util.SessionHolder;
import com.quectel.pay.module.merchant.dto.PayChannelDto;
import com.quectel.pay.module.merchant.service.PayChannelService;
import com.quectel.pay.module.order.constants.OrderConstants;
import com.quectel.pay.module.order.dto.PayOrderDto;
import com.quectel.pay.module.order.dto.response.OrderCreatedResponseDto;
import com.quectel.pay.module.order.service.PayOrderRefundService;
import com.quectel.pay.module.order.service.PayOrderService;
import com.quectel.sdk.officialaccounts.OfficialAccountsUtils;
import com.quectel.util.common.JacksonUtils;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author cl
 */
@RestController
@RequestMapping("pay")
@Tag(name = "PayController", description = "支付下单相关")
public class PayController extends BaseController {

    @DubboReference
    private PayOrderService orderService;
    @DubboReference
    private PayOrderRefundService orderRefundService;
    @DubboReference
    private PayChannelService payChannelService;
    @DubboReference
    private MerchantVillageService merchantVillageService;

    @Autowired
    private PayBusiness payBusiness;


    @GetMapping("getAliJSSDKConfig")
    @Operation(summary = "支付宝相关配置 动态支付需要")
    public Response<Map<String, String>> getAliJSSDKConfig(
            @Parameter(description = "小区id") @RequestParam Long villageId,
            @Parameter(description = "业务类型 比如：PropertyFee") @RequestParam String businessType
    ) {

        MerchantVillageDto merchantVillageDto = merchantVillageService.queryByVillageAndBusiness(villageId, businessType);
        if (merchantVillageDto == null) {
            return Response.error("公众号没有正确配置");
        }
        PayChannelDto payChannelDto = payChannelService.selectByMchIdAndPayType(merchantVillageDto.getMerchantId(), SystemConstants.PayConfigType.ZHB.getType());
        if (payChannelDto == null) {
            return Response.error("公众号没有正确配置");
        }
        PayChannelDto.WeChatJSAPIChannelConfig payConfig =
                JacksonUtils.parse(payChannelDto.getPayConfig(), PayChannelDto.WeChatJSAPIChannelConfig.class);
        Map<String, String> respMap = new HashMap<>();
        respMap.put("appId", payConfig.getAppId());

        return Response.<Map<String, String>>ok().wrap(respMap);
    }

    @GetMapping("getWxJSSDKConfig")
    @Operation(summary = "微信相关配置 动态支付需要")
    public Response<Map<String, String>> getWxJSSDKConfig(
            @Parameter(description = "当前页面") @RequestParam String currentPageUrl,
            @Parameter(description = "小区id") @RequestParam Long villageId,
            @Parameter(description = "业务类型 比如：PropertyFee") @RequestParam String businessType
    ) {

        MerchantVillageDto merchantVillageDto = merchantVillageService.queryByVillageAndBusiness(villageId, businessType);
        if (merchantVillageDto == null) {
            return Response.error("公众号没有正确配置");
        }
        PayChannelDto payChannelDto = payChannelService.selectByMchIdAndPayType(merchantVillageDto.getMerchantId(), SystemConstants.PayConfigType.WX_JSAPI.getType());
        if (payChannelDto == null) {
            return Response.error("公众号没有正确配置");
        }
        PayChannelDto.WeChatJSAPIChannelConfig payConfig =
                JacksonUtils.parse(payChannelDto.getPayConfig(), PayChannelDto.WeChatJSAPIChannelConfig.class);


        return Response.<Map<String, String>>ok().wrap(OfficialAccountsUtils.getWxJSSDKConfig(payConfig.getAppId(), payConfig.getSecret(), currentPageUrl));
    }

    @PostMapping("createOrder")
    @Operation(summary = "创建订单")
    public Response<OrderCreatedResponseDto> createOrder(@RequestBody @Validated CreateOrderRequest req) {
        LoginMobileUserSession loginMobileUserSession = SessionHolder.getLoginMobileUserSession();
        Preconditions.checkNotNull(loginMobileUserSession);
        req.setBuyerId(SystemConstants.buildPlatformUserUniqueFlag(loginMobileUserSession.getOfficialAccountsType()
                , loginMobileUserSession.getAppId(), loginMobileUserSession.getOpenId()));

        Response<OrderCreatedResponseDto> response = payBusiness.createOrder(SystemConstants.ApiPath.MOBILE_PATH, req);
        if (!response.isSuccess()) {
            return response;
        }
        return response;
    }

    @GetMapping("repayParamsQuery")
    @Operation(summary = "重新支付")
    public Response<OrderCreatedResponseDto> repayParamsQuery(@RequestParam String outTradeNo) {
        PayOrderDto payOrderDto = orderService.selectByOutTradeNo(outTradeNo);
        if (payOrderDto == null) {
            return Response.error("订单不存在");
        }
        if (!OrderConstants.Status.INIT.getStatusValue().equals(payOrderDto.getStatus())) {
            return Response.error("只有初始化订单才允许重新支付");
        }
        return Response.<OrderCreatedResponseDto>ok().wrap(JacksonUtils.parse(payOrderDto.getRedoValue(), OrderCreatedResponseDto.class));
    }

    @PostMapping("cancelOrder")
    @Operation(summary = "取消订单")
    public Response<Object> cancelOrder(@RequestBody String outTradeNo) {
        Response<Object> resp = payBusiness.cancelOrder(outTradeNo);
        if (!resp.isSuccess()) {
            return resp;
        }
        return Response.ok();
    }


}
